﻿using System;
using System.Collections.Generic;
using Raven.Imports.Newtonsoft.Json;
using Raven.Imports.Newtonsoft.Json.Converters;

namespace ConsoleApplication1
{
    public class JSONCustomDateConverter : DateTimeConverterBase
    {
        private TimeZoneInfo _timeZoneInfo;
        private string _dateFormat;

        public JSONCustomDateConverter(string dateFormat, TimeZoneInfo timeZoneInfo)
        {
            _dateFormat = dateFormat;
            _timeZoneInfo = timeZoneInfo;
        }

        public override bool CanConvert(Type objectType)
        {
            return objectType == typeof(DateTime);
        }

        public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer)
        {
            throw new NotImplementedException();
        }

        public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer)
        {
            writer.WriteValue(TimeZoneInfo.ConvertTime(Convert.ToDateTime(value), _timeZoneInfo).ToString(_dateFormat));
            writer.Flush();
        }
    }


    class JsonTest
    {
        public static void Test1()
        {

            DateTime? myObject = DateTime.Now;
            //myObject.Value.Kind=DateTimeKind.Utc;
            var jsonString = JsonConvert.SerializeObject(myObject, Formatting.None, new JsonSerializerSettings
            {
                NullValueHandling = NullValueHandling.Ignore,
                Converters = new List<JsonConverter>() { new JSONCustomDateConverter("yyyy-MM-dd HH:mm:ss", TimeZoneInfo.Local) }
            });
            jsonString = "\"2015-09-18\"";
            DateTime? result = JsonConvert.DeserializeObject<DateTime?>(jsonString);
        }
    }


}
